package com.woniuxy.service.impl;

import com.woniuxy.entity.Menu;
import com.woniuxy.mapper.MenuMapper;
import com.woniuxy.service.MenuService;
import com.woniuxy.util.GetUserContent;
import com.woniuxy.util.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HP
 * @version 1.0
 * @project
 * @description
 * @date 2024/4/8 15:34:18
 */

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;


    //根据用户id查询所有菜单
    //1.先找出所有的父菜单
    //2.然后让所有的父菜单找出自己对应的子菜单
    @Override
    public ResponseData<?> queryAllMenus()  {
        try {
            Map userInfo = GetUserContent.getUserInfo();
            Long userId = (long)userInfo.get("userId");
            List<Menu> menus = menuMapper.queryAllMenus(userId.intValue());
            //找出所有的父菜单
            List<Menu> parentMenu = menus.stream()
                    .filter(e -> e.getParentId().equals(-1))
                    .collect(Collectors.toList());
            //找出所有的子菜单
            for (Menu menu : parentMenu) {//循环父菜单
                List<Menu> childMenu = new ArrayList<>();
                for (Menu menu1 : menus) {//循环所有菜单
                    if (menu.getId().equals(menu1.getParentId())) {
                        //父菜单的Id 等于 菜单ParentId 说明是父菜单的子菜单
                        childMenu.add(menu1);
                    }
                }
                menu.setChildMenu(childMenu);//子菜单放入父菜单的属性中
            }

            return new ResponseData<>().ok(parentMenu);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
